package msg.domain;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class Schedule {
	private List<Program> scheduledPrograms = new ArrayList<Program>();

	public Program addProgram(String programName, String episodeName,
			int channel, Date startDateTime, int lengthInMinutes) {

		TimeSlot timeSlot = new TimeSlot(channel, startDateTime,
				lengthInMinutes);

		if (conflictsWithOtherTimeSlots(timeSlot)) {
			throw new ConflictingProgramException();
		}

		Program program = new Program(programName, episodeName, timeSlot);
		scheduledPrograms.add(program);
		return program;
	}

	private boolean conflictsWithOtherTimeSlots(TimeSlot timeSlot) {
		for (Program current : scheduledPrograms) {
			if (current.timeSlot.conflictsWith(timeSlot)) {
				return true;
			}
		}

		return false;
	}

	public void removeProgramById(String programIdToRemove) {
		for (Program program : scheduledPrograms) {
			if (programIdToRemove.equals(program.getId())) {
				scheduledPrograms.remove(program);
				break;
			}
		}

	}

	public List<Program> findProgramsNamedOn(String programName, int channel) {
		List<Program> result = new ArrayList<Program>();

		for (Program program : scheduledPrograms) {
			if (program.timeSlot.channel == channel
					&& program.programName.equals(programName)) {
				result.add(program);
			}
		}

		return result;
	}

	public void clear() {
		scheduledPrograms.clear();
	}
}